#!/usr/bin/env python
# coding: utf-8
'''
@File   :boot.py
@Author :youxinweizhi
@Date   :2020/7/16
@Github :https://github.com/youxinweizhi
'''

from machine import Timer
import ujson
from simple import MQTTClient

SERVER = "iot2.bigiot.xyz"#不用改
CLIENT_ID = "110"         #随便写
TOPIC = "username"        #登录的同户名
username="username"       #登录的同户名
password="******"         #登录的密码

t_ping=Timer(-1)          #定时器心跳

def sub_cb(topic, msg):   #收到的服务器消息处理函数
    print(msg)
    pub(1,2)#回复自定义语音

def pub(topic,msg):       #自定义语音函数
    text='哈哈哈哈'       #自定义语音内容
    TOP='user/revert'
    c.publish(topic=TOP,msg=text.encode(''))

def pp(t):               #心跳函数
    c.ping()
           
def main(server=SERVER): #主程序不用改
    global c
    c = MQTTClient(CLIENT_ID, server,1883,username,password)
    c.set_callback(sub_cb)
    try:
        c.connect()
        c.subscribe(TOPIC)
        print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
    except:
        print('no intnet')
    if c.res==0:
      t_ping.init(period=50000,mode=Timer.PERIODIC,callback=pp)      
      while 1:
          c.wait_msg()     
    else:
      t_ping.deinit()
      machine.reset()
      
main()

















